package com.example.lexiangbackend.controller;

import com.example.lexiangbackend.entity.User;
import com.example.lexiangbackend.entity.Music;
import com.example.lexiangbackend.entity.MusicCategory;
import com.example.lexiangbackend.service.AuthService;
import com.example.lexiangbackend.service.MusicService;
import com.example.lexiangbackend.service.CategoryService;
import com.example.lexiangbackend.service.UserService;
import com.example.lexiangbackend.dto.AdminLoginRequest;
import com.example.lexiangbackend.dto.AuthResponse;
import com.example.lexiangbackend.dto.MusicUploadRequest;
import com.example.lexiangbackend.dto.CategoryRequest;
import com.example.lexiangbackend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "http://localhost:8080")
public class AdminController {

    @Autowired
    private AuthService authService;
    
    @Autowired
    private MusicService musicService;
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRepository userRepository;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public ResponseEntity<AuthResponse> adminLogin(@Valid @RequestBody AdminLoginRequest request) {
        try {
            AuthResponse response = authService.authenticateAdmin(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 管理员个人资料
     */
    @GetMapping("/profile")
    public ResponseEntity<AuthResponse> getAdminProfile(@RequestHeader("Authorization") String token) {
        try {
            // 提取token（移除Bearer前缀）
            String jwtToken = token.substring(7);
            User admin = authService.verifyToken(jwtToken);
            String role = authService.extractRoleFromToken(jwtToken);
            
            // 验证是否为管理员
            if (!"ADMIN".equals(role)) {
                return ResponseEntity.badRequest()
                        .body(new AuthResponse(false, "权限不足", null, null, null));
            }
            
            return ResponseEntity.ok(new AuthResponse(true, "获取管理员信息成功", jwtToken, role, admin));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, "获取管理员信息失败", null, null, null));
        }
    }

    // ================================ 用户管理 ================================
    
    /**
     * 获取所有用户列表（分页）
     */
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            Pageable pageable = PageRequest.of(page, size);
            Page<User> users = userRepository.findAll(pageable);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取用户列表成功");
            response.put("users", users.getContent());
            response.put("totalElements", users.getTotalElements());
            response.put("totalPages", users.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取用户列表失败"));
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<?> deleteUser(
            @PathVariable Long userId,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            userService.deleteUser(userId);
            return ResponseEntity.ok(createSuccessResponse("删除用户成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("删除用户失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/users/{userId}")
    public ResponseEntity<?> getUserDetails(
            @PathVariable Long userId,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            User user = userService.getUserById(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取用户详情成功");
            response.put("user", user);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取用户详情失败"));
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/users/{userId}")
    public ResponseEntity<?> updateUser(
            @PathVariable Long userId,
            @RequestBody Map<String, Object> updateData,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            User user = userService.updateUser(userId, updateData);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "用户信息更新成功");
            response.put("user", user);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("更新用户信息失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除用户
     */
    @PostMapping("/users/batch-delete")
    public ResponseEntity<?> batchDeleteUsers(
            @RequestBody Map<String, Object> requestData,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            // 处理userIds的类型转换问题
            @SuppressWarnings("unchecked")
            List<Object> userIdsObj = (List<Object>) requestData.get("userIds");
            if (userIdsObj == null || userIdsObj.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要删除的用户"));
            }
            
            // 将Object转换为Long
            List<Long> userIds = userIdsObj.stream()
                    .map(obj -> {
                        if (obj instanceof Integer) {
                            return ((Integer) obj).longValue();
                        } else if (obj instanceof Long) {
                            return (Long) obj;
                        } else if (obj instanceof String) {
                            return Long.parseLong((String) obj);
                        } else {
                            throw new RuntimeException("无效的用户ID格式: " + obj);
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            userService.batchDeleteUsers(userIds);
            return ResponseEntity.ok(createSuccessResponse("批量删除用户成功，共删除 " + userIds.size() + " 个用户"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("批量删除用户失败: " + e.getMessage()));
        }
    }

    /**
     * 批量更新用户状态
     */
    @PostMapping("/users/batch-status")
    public ResponseEntity<?> batchUpdateUserStatus(
            @RequestBody Map<String, Object> requestData,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            // 处理userIds的类型转换问题
            @SuppressWarnings("unchecked")
            List<Object> userIdsObj = (List<Object>) requestData.get("userIds");
            Integer status = (Integer) requestData.get("status");
            
            if (userIdsObj == null || userIdsObj.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要更新的用户"));
            }
            if (status == null || (status != 0 && status != 1)) {
                return ResponseEntity.badRequest().body(createErrorResponse("状态值无效"));
            }
            
            // 将Object转换为Long
            List<Long> userIds = userIdsObj.stream()
                    .map(obj -> {
                        if (obj instanceof Integer) {
                            return ((Integer) obj).longValue();
                        } else if (obj instanceof Long) {
                            return (Long) obj;
                        } else if (obj instanceof String) {
                            return Long.parseLong((String) obj);
                        } else {
                            throw new RuntimeException("无效的用户ID格式: " + obj);
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            userService.batchUpdateUserStatus(userIds, status);
            String action = status == 0 ? "解锁" : "锁定";
            return ResponseEntity.ok(createSuccessResponse("批量" + action + "用户成功，共处理 " + userIds.size() + " 个用户"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("批量更新用户状态失败: " + e.getMessage()));
        }
    }

    // ================================ 音乐管理 ================================

    /**
     * 上传音乐
     */
    @PostMapping("/music")
    public ResponseEntity<?> uploadMusic(
            @Valid @RequestBody MusicUploadRequest request,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            Music music = musicService.uploadMusic(request);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "音乐上传成功");
            response.put("music", music);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("音乐上传失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有音乐列表（分页）
     */
    @GetMapping("/music")
    public ResponseEntity<?> getAllMusic(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            Page<Music> musicPage = musicService.getAllMusic(page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取音乐列表成功");
            response.put("music", musicPage.getContent());
            response.put("totalElements", musicPage.getTotalElements());
            response.put("totalPages", musicPage.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取音乐列表失败"));
        }
    }

    /**
     * 更新音乐信息
     */
    @PutMapping("/music/{musicId}")
    public ResponseEntity<?> updateMusic(
            @PathVariable Long musicId,
            @Valid @RequestBody MusicUploadRequest request,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            Music music = musicService.updateMusic(musicId, request);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "音乐更新成功");
            response.put("music", music);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("音乐更新失败: " + e.getMessage()));
        }
    }

    /**
     * 删除音乐
     */
    @DeleteMapping("/music/{musicId}")
    public ResponseEntity<?> deleteMusic(
            @PathVariable Long musicId,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            musicService.deleteMusic(musicId);
            return ResponseEntity.ok(createSuccessResponse("删除音乐成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("删除音乐失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除音乐
     */
    @PostMapping("/music/batch-delete")
    public ResponseEntity<?> batchDeleteMusic(
            @RequestBody Map<String, Object> requestData,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            @SuppressWarnings("unchecked")
            List<Object> musicIdsObj = (List<Object>) requestData.get("musicIds");
            if (musicIdsObj == null || musicIdsObj.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要删除的音乐"));
            }
            
            List<Long> musicIds = musicIdsObj.stream()
                    .map(obj -> Long.valueOf(obj.toString()))
                    .toList();
            
            // 逐个删除音乐（包括文件）
            int successCount = 0;
            int failCount = 0;
            for (Long musicId : musicIds) {
                try {
                    musicService.deleteMusic(musicId);
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    System.err.println("删除音乐 " + musicId + " 失败: " + e.getMessage());
                }
            }
            
            String message = String.format("批量删除完成，成功: %d，失败: %d", successCount, failCount);
            Map<String, Object> response = createSuccessResponse(message);
            response.put("successCount", successCount);
            response.put("failCount", failCount);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("批量删除音乐失败: " + e.getMessage()));
        }
    }

    // ================================ 分类管理 ================================

    /**
     * 创建音乐分类
     */
    @PostMapping("/categories")
    public ResponseEntity<?> createCategory(
            @Valid @RequestBody CategoryRequest request,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            MusicCategory category = categoryService.createCategory(request);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "分类创建成功");
            response.put("category", category);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("分类创建失败: " + e.getMessage()));
        }
    }

    /**
     * 获取分类列表（分页）
     */
    @GetMapping("/categories")
    public ResponseEntity<?> getCategories(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "sortOrder") String sortBy) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            Page<MusicCategory> categories = categoryService.getCategories(page, size, sortBy);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取分类列表成功");
            response.put("categories", categories.getContent());
            response.put("totalElements", categories.getTotalElements());
            response.put("totalPages", categories.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取分类列表失败"));
        }
    }

    /**
     * 获取所有分类（不分页，用于下拉选择）
     */
    @GetMapping("/categories/all")
    public ResponseEntity<?> getAllCategories(@RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            List<MusicCategory> categories = categoryService.getAllCategories();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取分类列表成功");
            response.put("categories", categories);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取分类列表失败"));
        }
    }

    /**
     * 获取分类详情
     */
    @GetMapping("/categories/{categoryId}")
    public ResponseEntity<?> getCategoryDetails(
            @PathVariable Long categoryId,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            MusicCategory category = categoryService.getCategoryById(categoryId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取分类详情成功");
            response.put("category", category);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取分类详情失败"));
        }
    }

    /**
     * 更新分类
     */
    @PutMapping("/categories/{categoryId}")
    public ResponseEntity<?> updateCategory(
            @PathVariable Long categoryId,
            @Valid @RequestBody CategoryRequest request,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            MusicCategory category = categoryService.updateCategory(categoryId, request);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "分类更新成功");
            response.put("category", category);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("分类更新失败: " + e.getMessage()));
        }
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/categories/{categoryId}")
    public ResponseEntity<?> deleteCategory(
            @PathVariable Long categoryId,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            categoryService.deleteCategory(categoryId);
            return ResponseEntity.ok(createSuccessResponse("删除分类成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("删除分类失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除分类
     */
    @PostMapping("/categories/batch-delete")
    public ResponseEntity<?> batchDeleteCategories(
            @RequestBody Map<String, Object> requestData,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            @SuppressWarnings("unchecked")
            List<Object> categoryIdsObj = (List<Object>) requestData.get("categoryIds");
            if (categoryIdsObj == null || categoryIdsObj.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要删除的分类"));
            }
            
            List<Long> categoryIds = categoryIdsObj.stream()
                    .map(obj -> Long.valueOf(obj.toString()))
                    .toList();
            
            categoryService.deleteCategoriesBatch(categoryIds);
            return ResponseEntity.ok(createSuccessResponse("批量删除分类成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("批量删除分类失败: " + e.getMessage()));
        }
    }

    /**
     * 批量更新分类状态
     */
    @PostMapping("/categories/batch-status")
    public ResponseEntity<?> batchUpdateCategoryStatus(
            @RequestBody Map<String, Object> requestData,
            @RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            @SuppressWarnings("unchecked")
            List<Object> categoryIdsObj = (List<Object>) requestData.get("categoryIds");
            Object statusObj = requestData.get("status");
            
            if (categoryIdsObj == null || categoryIdsObj.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要更新的分类"));
            }
            
            if (statusObj == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("请提供状态值"));
            }
            
            List<Long> categoryIds = categoryIdsObj.stream()
                    .map(obj -> Long.valueOf(obj.toString()))
                    .toList();
            
            Integer status = Integer.valueOf(statusObj.toString());
            categoryService.updateCategoriesStatus(categoryIds, status);
            
            return ResponseEntity.ok(createSuccessResponse("批量更新分类状态成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("批量更新分类状态失败: " + e.getMessage()));
        }
    }

    // ================================ 统计信息 ================================

    /**
     * 获取管理后台统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<?> getStatistics(@RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            long userCount = userRepository.count();
            long musicCount = musicService.getMusicCount();
            long categoryCount = categoryService.getCategoryCount();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取统计信息成功");
            response.put("userCount", userCount);
            response.put("musicCount", musicCount);
            response.put("categoryCount", categoryCount);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取统计信息失败"));
        }
    }

    /**
     * 获取热门音乐
     */
    @GetMapping("/hot-music")
    public ResponseEntity<?> getHotMusic(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "5") int limit) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            Page<Music> hotMusic = musicService.getHotMusic(0, limit);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取热门音乐成功");
            response.put("music", hotMusic.getContent());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("获取热门音乐失败"));
        }
    }

    /**
     * 清理孤立文件
     */
    @PostMapping("/clean-files")
    public ResponseEntity<?> cleanOrphanFiles(@RequestHeader("Authorization") String token) {
        try {
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足"));
            }
            
            musicService.cleanOrphanFiles();
            return ResponseEntity.ok(createSuccessResponse("孤立文件清理完成"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("清理文件失败: " + e.getMessage()));
        }
    }

    // ================================ 辅助方法 ================================

    private boolean isAdmin(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return false;
            }
            
            String jwtToken = token.substring(7);
            String role = authService.extractRoleFromToken(jwtToken);
            return "ADMIN".equals(role);
        } catch (Exception e) {
            return false;
        }
    }

    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        return response;
    }

    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
} 